class EnterItem < ActiveRecord::Base
  
  validates :order_made_id,
    :presence => true,
    :if => 'order_made_item_id.present?'
  validates :entered_count,
    :numericality => {
      :greater_than_or_equal_to => 1,
      :less_than_or_equal_to => Proc.new { |enter_item| enter_item.order_made_item.present? ? enter_item.order_made_item.order_made_count : 5000000 }
    }
    
  validates :furniture_id,
    :entered_on,
    :presence =>true
    
  belongs_to :order
  belongs_to :order_item
  belongs_to :installation
  belongs_to :install_item
  belongs_to :furniture
  belongs_to :order_made
  belongs_to :order_made_item
  belongs_to :furniture_logistic_stat
  belongs_to :feed
  has_many :feeds, :dependent => :destroy
  has_one :furniture_logistic_stat_order_item, :dependent => :destroy
  
  after_create do |enter_item|
    if enter_item.order_item.present?
      # OrderItem::FactoryOrderMade
      enter_item.furniture_logistic_stat_order_item = FurnitureLogisticStatOrderItem.new(
        :enter_item_id => enter_item.id,
        :order_item_id => enter_item.order_item_id,
        :furniture_logistic_stat_id => enter_item.furniture_logistic_stat_id,
        :ordered_count => enter_item.entered_count
      ) 
    end
    # create feed
    enter_item.update_attribute :feed, Feed::EnterItemCreated.create!(:enter_item_id => enter_item.id)
  end
  
  after_save do |enter_item|
#    enter_item.order_item.try(:'reset_feed!')
#    enter_item.install_item.try(:'reset_feed!')
#    enter_item.order_made_item.reset_feed!

    enter_item.furniture_logistic_stat.reset_entered_count!
    enter_item.furniture_logistic_stat_order_item.update_attribute(:ordered_count, enter_item.entered_count) if enter_item.furniture_logistic_stat_order_item.present?
  end
  
  after_destroy do |enter_item|
#    enter_item.order_item.try(:'reset_feed!')
#    enter_item.install_item.try(:'reset_feed!')
#    enter_item.order_made_item.reset_feed!
    enter_item.furniture_logistic_stat.reset_entered_count!    
  end

  def status
    ActiveSupport::StringInquirer.new(feed.code)
  end

#  def reset_feed!
#    update_attribute :feed_id, Feed.where(:enter_item_id => id).last.id
#  end
end
